<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Book extends CI_Controller {
	function __construct(){
		parent:: __construct();
		$this->load->model("mod_book");
		$this->load->library('cart');
		$this->load->library('form_validation');
		$this->load->library('email');
		$this->load->helper('string');
	
	}

	function reviewOrder(){
		$data["page"] = "reviewOrder";
		$user_shippingid = $this->session->userdata("user_shippingid");
		$shippingData = $this->mod_book->getShippingAddressPrice($user_shippingid);
		$data['shippingAddress'] = $shippingData->row()->shipping_price;
		$this->load->view("index",$data);
	}


	function  getDetailShipping($id){
		$datas = $this->mod_book->getDetailShipping($id)->row();
		header('Content-Type: application/json');
        echo json_encode($datas);
	}
	function deleteDetailShipping($id){
		$this->mod_book->deleteDetailShipping($id);
		redirect("book/orderCard");
	}
	function getAllShippingAddress($id){
		$userId = $this->session->userdata("userId");
		$result = $this->mod_book->getAllShippingAddress($userId,$id)->result();
		header('Content-Type: application/json');
        echo json_encode($result);
	}
	function addNewShippingAddess(){
		$id = $this->input->post('shippingId');
		$mobile = $this->input->post('mobile');
		$sipCode = $this->input->post('sipCode');
		$province = $this->input->post('province');
		$city = $this->input->post('city');
		$apartment = $this->input->post('apartment');
		$street = $this->input->post('street');
		$country = $this->input->post('country');
		$contactName = $this->input->post('contactName');
		$arr = array(

			"fullname"=>$contactName,
			"countryid"=>$country,
			"street"=>$street,
			"city"=>$city,
			"state"=>$province,
			"zipCode"=>$sipCode,
			"mobile"=>$mobile,
			"apartment"=>$apartment,
			"userId"=>$this->session->userdata("userId"),
			"email"=>$this->session->userdata("email")
		);
		$this->mod_book->addNewShippingAddess($arr);
		redirect("book/orderCard");
	}

	function updateShippingAddess(){
		$id = $this->input->post('shippingId');
		$mobile = $this->input->post('mobile');
		$sipCode = $this->input->post('sipCode');
		$province = $this->input->post('province');
		$city = $this->input->post('city');
		$apartment = $this->input->post('apartment');
		$street = $this->input->post('street');
		$country = $this->input->post('country');
		$contactName = $this->input->post('contactName');
		$arr = array(
			"fullname"=>$contactName,
			"countryid"=>$country,
			"street"=>$street,
			"city"=>$city,
			"state"=>$province,
			"zipCode"=>$sipCode,
			"mobile"=>$mobile,
			"apartment"=>$apartment
		);
		$this->mod_book->updateShippingAddess($id,$arr);
		redirect("book/orderCard");
	}

	
	// function bookPayed(){
	// 	$date = date("Y-m-d");
	// 	$idUser = $this->session->userdata("orderUserId");
	// 	foreach($this->cart->contents() as $items)
	// 		    {
	// 		        // Create an array with the products rowid's and quantities. 
	// 		        $data[] = array(
	// 		           'userId'=>$idUser,
	// 		           'productId' => $items['id'],
	// 		           'price'=>$items['price'],
	// 		           'qty'   => $items['qty'],
	// 		           'bookName'=>$items['name'],
	// 		           'images'   => $items['img'],
	// 		           'dateBook'=>$date,
	// 		           'pay'=>1
	// 		        );    
	// 	}

	// 	$this->mod_book->addOrderBook($data);
	// 	$this->cart->destroy();
	// 	$this->session->unset_userdata("orderUserId");
	// 	redirect("book/addCartDone");
	// }

	function bookPayed(){
		
		$data = $this->session->userdata("orderBookId");
		$this->mod_book->payOrderBook($data);
		$this->cart->destroy();
		$this->session->unset_userdata("orderUserId");
		$this->session->unset_userdata("orderBookId");
		redirect("book/addCartDone");
	}

	function addCartDone(){
		$data["page"] = "done";
		$this->load->view('index',$data);
	}


	public function do_purchase(){

	//	$config['business'] 			= 'pierolivi@hotmail.com';
		$config['business'] 			= 'pierolivi@hotmail.com';

		$config['cpp_header_image'] 	= ''; //Image header url [750 pixels wide by 90 pixels high]
		$config['return'] 				= base_url().'index.php/book/bookPayed';
		$config['cancel_return'] 		= base_url().'index.php/book/cancel_payment';
		$config['notify_url'] 			= ''; //IPN Post
		$config["currency_code"] 		= 'EUR';
		$config["lc"] = 'FR';
		//$config['production'] 			= FALSE; //Its false by default and will use sandbox
		$config['production'] 			= TRUE; //Its false by default and will use sandbox

		$config["invoice"]				= random_string('numeric',8); //The invoice id
		
		
		$this->load->library('paypal',$config);
			//$total = count($this->cart->contents());
			//$item = $this->input->post('rowid');
			//$qty = $this->input->post('qty');
			//$productName = $this->input->post('productName');
		   // $shipping = $this->input->post("shipping");
			//$price = $this->input->post('price');
			
			    // Cycle true all items and update them
			    // for($i=0;$i < $total;$i++)
			    // {

			    // $total_price = $price[$i];
			    //     // Create an array with the products rowid's and quantities. 
			        
			         
			    //   $this->paypal->add($productName[$i],$total_price,$qty[$i],$shipping[$i]); //First item
			    // }
			$date = date("Y-m-d");
			$orderBookId  = array();
			$user_shippingid = $this->session->userdata("user_shippingid");
			$shippingData = $this->mod_book->getShippingAddressPrice($user_shippingid);
			$shippingAddress = $shippingData->row()->shipping_price;


			//// Add data to table user_order
			$data_order_user = array(
							'user_shipping_id'=>$user_shippingid,
							'userid'=>$this->session->userdata("userId"),
							'order_date'=>$date

					);

				$order_user_id = $this->mod_book->addOrderuser($data_order_user);

			foreach($this->cart->contents() as $items)
				    {

				        // Create an array with the products rowid's and quantities. 
				     
				     //echo iconv(mb_detect_encoding($items['name'], mb_detect_order(), true), "UTF-8", $items['name']);
				    // echo $comments = mb_convert_encoding($items['name'],"UTF-8", "auto");;
				    // exit();
				    	
				header('Content-type: text/plain; charset=utf-8');
				 $nameItem = $items['name'];
				$totalShippingItem = $items['qty']*$shippingAddress;
				$this->paypal->add($nameItem,$items['price'],$items['qty'],$totalShippingItem);
				

				 $data = array(
				           'order_user_id'=>$order_user_id,
				           'productId' => $items['id'],
				           'price'=>$items['price'],
				           'qty'   => $items['qty'],
				           'bookName'=>$items['name'],
				           'images'   => $items['img'],				           
				           'is_pay'=>0,
				           'is_get'=>0,
				           'shipping_price'=> $totalShippingItem
				        ); 
				
				$orderBookId[] = $this->mod_book->addOrderBookAll($data);   
			}

		   
		$this->session->set_userdata("orderBookId",$orderBookId);
		//$this->cart->destroy();
		//$this->session->sess_destroy();
		$this->cart->destroy();
		$this->session->unset_userdata("user_shippingid");
		
		$this->session->unset_userdata("registerInfor");
	    $this->paypal->pay(); //Proccess the payment
		

	}

	/** Deverloper Chantra**/
	function addCart($all=NULL){
		$id = $this->input->post('postId');
		$qty = $this->input->post('qty');
		$price = $this->input->post('price');
		$name = $this->input->post('name');
		$img = $this->input->post('img');
		$shipping = $this->input->post("shipping");

		  $data = array(
                'id'      => $id,
                'qty'     => $qty,
                'price'   => $price,
                'name'    => $name,
                'img'	  => $img,
                'shipping'=>$shipping
            );
            $this->cart->insert($data); 
            if($all == NULL){
            	echo 1;
            }else{
            	//redirect("book/orderCard");
            	echo 2;
            }
	}
	function addCart_BuyOne(){

		$id = $this->input->post('postId');
		$qty = $this->input->post('qty');
		$price = $this->input->post('price');
		$name = $this->input->post('bookName');
		$img = $this->input->post('img');
		$shipping = $this->input->post("shipping");

		  $data = array(
                'id'      => $id,
                'qty'     => $qty,
                'price'   => $price,
                'name'    => $name,
                'img'	  => $img,
                'shipping'=>$shipping
            );
           $rowId =  $this->cart->insert($data); 
           // $last = end($this->cart->contents($rowId));
    		echo  1;
          
            
	}

	function detailBook($book_id){
		$arr = explode("_", $book_id);
		$id = $arr[1];
		$data["page"] = "detailBook";
		$data['result'] = $this->mod_book->getDetailBook($id);
		$this->load->view('index',$data);
	}
	function detailBookAll($book_id){
		$arr = explode("_", $book_id);
		$id = $arr[1];
		$data["page"] = "detailBookAll";
		$data['result'] = $this->mod_book->getDetailBook($id);
		$this->load->view('index',$data);
	}

	/** End chantra**/
	public function index()
	{
		$data["page"] = "home";
		//$data["bookData"] = $this->mod_book->getBook();
		$this->load->view('index',$data);
	}
	function books(){
		$data["page"] = "book";
		$data["bookData"] = $this->mod_book->getBook();
		$this->load->view('index',$data);
	}

	


	function addRegister(){  
  $this->form_validation->set_rules('email', 'Email', 'trim|required');
  $this->form_validation->set_rules('agree', 'Check Book', 'required');
  if($this->form_validation->run() === false){
   redirect("book/register");
  }else{ 

   $email = $this->input->post("email");
   $agree = $this->input->post("agree");  
   $id = $this->mod_book->addRegisterEmail($email,$agree);
     $to = $email;
     $subject = "editiondelaplushautetour";      
     $headers = "From: www.editiondelaplushautetour.com" . "\r\n";    
          $message='
         <html>
         <head>
         	<title>Verify Email</title>
         </head>
         <body>
         
        	<h4>Hello Customer,<br/><br/>


      		Thanks for verifying your account!<br/><br/>


        	 Please click the following link to verify your email address with us at Garena Security Center:</h4><br/>

        	 <a class="btn btn-danger" href="'.base_url().'index.php/book/validateEmail/'.$id.'">'.base_url().'index.php/book/validateEmail/'.$id.'</a>

         </body>
         </html>';
  
      $sendMail = mail($to, $subject, $message, $headers); 
      if($sendMail){
      	$this->session->set_userdata("usermail",$email);
      }else{
 		$this->mod_book->deleteuserbymail($email);
        $this->session->unset_userdata('usermail'); 
       
      }                             
  redirect('book/register');
  }
      
 }

	function OrderExitUser(){
			//$count = count($this->cart->contents());
			//$item = $this->input->post('rowid');
			//$qty = $this->input->post('qty');
			$user_shippingid = $this->input->post("userOrderId");
			    // Cycle true all items and update them
			    // for($i=0;$i < $count;$i++)
			    // {
			    //    // Create an array with the products rowid's and quantities. 
			    //      $data = array(
			    //        'rowid' => $item[$i],
			    //        'qty'   => $qty[$i]
			    //     );
			    //     // Update the cart with the new information
			    //     $this->cart->update($data);
			    // }
			    $this->session->set_userdata("user_shippingid",$user_shippingid);
			    $this->session->set_userdata("registerInfor","sucess");

		redirect("book/reviewOrder");
	}



	function addOrderInfo(){
		$data['page'] = "orderCard";
		$data["error_zip"] = "";
		$ZIPREG=array(
			"US"=>"^\d{5}([\-]?\d{4})?$",
			"UK"=>"^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$",
			"DE"=>"\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b",
			"CA"=>"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$",
			"FR"=>"^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$",
			"IT"=>"^(V-|I-)?[0-9]{5}$",
			"AU"=>"^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$",
			"NL"=>"^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$",
			"ES"=>"^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$",
			"DK"=>"^([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}$",
			"SE"=>"^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$",
			"BE"=>"^[1-9]{1}[0-9]{3}$",
			"KH"=> "^\d{5}$",
			"IN"=>"^\d{6}$"
		);
		 
		
		$this->form_validation->set_rules("contactName","Contact Name","trim|required");
		$this->form_validation->set_rules("country","Country","trim|required");
		$this->form_validation->set_rules("street","Street","trim|required");
		$this->form_validation->set_rules("city","City","trim|required");
		$this->form_validation->set_rules("province","Province","trim|required");
		$this->form_validation->set_rules("sipCode","Zip Cord","trim|required");
		$this->form_validation->set_rules("mobile","Mobile","trim|required");
		$this->form_validation->set_rules("postOfficeId","Post Office","trim|required");
		$data["result_user"] = $this->mod_book->checkOrderExit($this->session->userdata("userId"));
		if($this->form_validation->run() == false){
				
				$this->load->view("index",$data);
		}else{
			$name = $this->input->post("contactName");
			$country = $this->input->post("country");
			$street = $this->input->post("street");
			$city = $this->input->post("city");
			$province = $this->input->post("province");
			$sipCode = $this->input->post("sipCode");
			$mobile = $this->input->post("mobile");
			$apartment = $this->input->post("apartment");
			$postOffice = $this->input->post("postOfficeId");
			$checkLocation = $this->mod_book->checkZipExit($sipCode);
			$getACountry = $this->mod_book->getACountry($country);
			$country_code = $getACountry->row()->country_code;
			
			if (!preg_match("/".$ZIPREG[$country_code]."/i",$sipCode)){
				$data["error_zip"]="<br />Please enter a valid ZIP or postal code.";
				$this->load->view("index",$data);
				//Validation failed, provided zip/postal code is not valid.
			} else {
				if($checkLocation == false){
				$user_shippingid = $this->mod_book->addOrderInfo($name,$country,$street,$city,$province,$sipCode,$mobile,$apartment,$postOffice);
				}else{
					$user_shippingid= $checkLocation->user_shipping_id;
				}
				$this->session->set_flashdata("sms_success","You are success");
				$this->session->set_userdata("registerInfor","sucess");
				$this->session->set_userdata("user_shippingid",$user_shippingid);

				redirect("book/reviewOrder");
			}

			
			//$total = count($this->cart->contents());
			//$item = $this->input->post('rowid');
			//$qty = $this->input->post('qty');
			//$productName = $this->input->post('productName');
			//$img = $this->input->post('img');
			// $price = $this->input->post('price');
			//     // Cycle true all items and update them
			//     for($i=0;$i < $total;$i++)
			//     {
			       
			//          $data = array(
			//            'rowid' => $item[$i],
			//            'qty'   => $qty[$i]
			//         );
			//         // Update the cart with the new information
			//         $this->cart->update($data);
			//     }
			
			
		}
	}

	function addNewShippingAddress(){
		$this->form_validation->set_rules("contactName","Contact Name","trim|required");
		$this->form_validation->set_rules("country","Country","trim|required");
		$this->form_validation->set_rules("street","Street","trim|required");
		$this->form_validation->set_rules("city","City","trim|required");
		$this->form_validation->set_rules("province","Province","trim|required");
		$this->form_validation->set_rules("sipCode","Zip Cord","trim|required");
		$this->form_validation->set_rules("mobile","Mobile","trim|required");
		if($this->form_validation->run() == false){

		}else{
			$name = $this->input->post("contactName");
			$country = $this->input->post("country");
			$street = $this->input->post("street");
			$city = $this->input->post("city");
			$province = $this->input->post("province");
			$sipCode = $this->input->post("sipCode");
			$mobile = $this->input->post("mobile");
			$apartment = $this->input->post("apartment");

			//$checkLocation = $this->mod_book->checkZipExit($sipCode);
			//if($checkLocation == false){
				$user_shippingid = $this->mod_book->addOrderInfo($name,$country,$street,$city,$province,$sipCode,$mobile,$apartment);
			//}else{
			//	echo '';
				//exit();
			//}
			
			//$total = count($this->cart->contents());
			//$item = $this->input->post('rowid');
			//$qty = $this->input->post('qty');
			//$productName = $this->input->post('productName');
			//$img = $this->input->post('img');
			// $price = $this->input->post('price');
			//     // Cycle true all items and update them
			//     for($i=0;$i < $total;$i++)
			//     {
			       
			//          $data = array(
			//            'rowid' => $item[$i],
			//            'qty'   => $qty[$i]
			//         );
			//         // Update the cart with the new information
			//         $this->cart->update($data);
			//     }
			
			$this->session->set_flashdata("sms_success","You are success");
			$this->session->set_userdata("registerInfor","sucess");
			$this->session->set_userdata("user_shippingid",$user_shippingid);
			redirect("book/do_purchase");
		}
	}
	
	function checkMailExit(){
		$mail = $this->input->post("email");
		$result = $this->mod_book->checkMailExit($mail);
		if($result->num_rows() > 0){
			echo 1;
		}else{
			echo 0;
		}
	}
	function orderCard(){
		if($this->session->userdata('loggedIn')){
			//echo $this->session->userdata("userId");
			//exit();
			$data["error_zip"] ="";
			$data["result_user"] = $this->mod_book->checkOrderExit($this->session->userdata("userId"));
			$data["page"] = "orderCard";
			$this->load->view('index',$data);
		}else{
			redirect("book/signIn");
		}
	}

	function login(){
		$this->form_validation->set_rules('email', 'Email', 'trim|required');
		$this->form_validation->set_rules('password', 'Password', 'trim|required');
		if($this->form_validation->run() === false){
			header('Content-Type: application/json');
	   		echo json_encode(array(
	   			'st' =>0,
	   			'email'=>form_error('email'),
	   			'password'=>form_error('password')
	   			)
	   		); 
		}else{

			$email = $this->input->post('email');
			$password = $this->input->post('password');
			$rowData = $this->mod_book->getUserProfile($email,$password);
			if($rowData){
				$ses_arr = array(
						"first_name"=>$rowData->firstname,
						"username"=>$rowData->firstname.' '.$rowData->lastname,
						"email"=>$rowData->email,
						"userId"=>$rowData->userid,
						"loggedIn"=>true
				);
				$this->session->set_userdata($ses_arr);
				header('Content-Type: application/json');
		   		echo json_encode(array(
		   			'st' =>2,
		   			'email'=>$email,
		   			'pass'=>$password
		   			)
		   		);
			}else{
				header('Content-Type: application/json');
		   		echo json_encode(array(
		   			'st' =>1,
		   			'error'=>'<p>Email or Password is invalid!</p>'
		   			)
		   		);
			}			
		}
	}

	


	function clearCard(){
		$this->cart->destroy();
		redirect('book/viewCart');
	}
	function register(){
		$data["page"] = "register";
		$this->load->view('index',$data);
	}
	function updateCart(){

		$total = $this->cart->total_items();
     
	    // Retrieve the posted information
	    $item = $this->input->post('rowid');
	    $qty = $this->input->post('qty');
	 
	    // Cycle true all items and update them
	    for($i=0;$i < $total;$i++)
	    {
	        // Create an array with the products rowid's and quantities. 
	        $data = array(
	           'rowid' => $item[$i],
	           'qty'   => $qty[$i]
	        );
	         
	        // Update the cart with the new information
	        $this->cart->update($data);
	    }
	    redirect('book/viewCart');
 
	}
	function removeCard(){
		$rowid = $this->input->post('id');
		if($rowid == "all"){
			$this->cart->destroy();

		}else{ 
		$data = array(
			'rowid' => $rowid,
			'qty' => 0
		);
		// Update cart data, after cancel.
		$this->cart->update($data);
		echo 'true';
		}
	}
	function viewCart(){
		$data['page'] = "viewCart";
		$this->load->view('index',$data);
	}
	
	
	function howToBuy(){
		$data["page"] = "howToBuy";
		$this->load->view('index',$data);
	}
	function about(){
		$data["page"] = "about";
		$this->load->view('index',$data);
	}
	function blog(){
		$data["page"] = "blog";
		$this->load->view('index',$data);
	}
	function contact(){
		$data["page"] = "contact";
		$this->load->view('index',$data);
	}




	// Thymeaks

	function clearCard_Order(){
		$this->cart->destroy();
		redirect('book/orderCard');
	}

	function updateCart_Order(){

		$total = $this->cart->total_items();
     
	    // Retrieve the posted information
	    $item = $this->input->post('rowid');
	    $qty = $this->input->post('qty');
	 
	    // Cycle true all items and update them
	    for($i=0;$i < $total;$i++)
	    {
	        // Create an array with the products rowid's and quantities. 
	        $data = array(
	           'rowid' => $item[$i],
	           'qty'   => $qty[$i]
	        );
	         
	        // Update the cart with the new information
	        $this->cart->update($data);
	    }
	    redirect('book/orderCard');
 
	}

	function home(){
		$data["page"] = "home";
		$this->load->view('index',$data);
	}


	// function form_signin(){
	// 	$data["page"] = "home";	
	// 	$this->form_validation->set_rules('txtusername', 'Username', 'trim|required');	
	// 	$this->form_validation->set_rules('txtpassword', 'Password', 'trim|required');
	// 	if($this->form_validation->run() == FALSE){
	// 			$this->load->view("index",$data);
	// 	}else{

	// 		$username = $this->input->post('txtusername');
	// 		$password = $this->input->post('txtpassword');
	// 		$dtuser = $this->mod_book->getuser($Username,$password);
	// 		if($dtuser > 0){
	// 			$this->session->set_userdata('username',$username);
	// 		}
	// 	}	
	// 	$this->load->view('index',$data);
	// }


	function signIn(){
		if($this->session->userdata("loggedIn")){
			redirect('book/orderCard');

		}else{
		$data['page'] = "signIn";
		$this->form_validation->set_rules('email', 'Email', 'trim|required');	
		$data['eorror'] = "";
		if($this->form_validation->run() == FALSE){
				$this->load->view('index',$data);
		}else{
			$email = $this->input->post('email');
			$password = $this->input->post('password');
			$customerValue = $this->input->post('customer');
			if($customerValue == true){ 
				$rowData = $this->mod_book->getUserProfile($email,$password);
				if($rowData){
					$ses_arr = array(
							"first_name"=>$rowData->firstname,
							"username"=>$rowData->firstname.' '.$rowData->lastname,
							"email"=>$rowData->email,
							"userId"=>$rowData->userid,
							"loggedIn"=>true
					);
					$this->session->set_userdata($ses_arr);
					redirect('book/orderCard');
				}else{
					$data['eorror'] = "Email or password invalid!";
					$this->load->view('index',$data);
				}
			}else{
				$result = $this->mod_book->checkMailExit($email);
				if($result->num_rows() > 0){
					$data['eorror'] = "Your email address registerd already!";
					$this->load->view('index',$data);
				}else{
					
					$arr = array(
						"email"=>$email,
						
					);
					$this->session->set_userdata($arr);
					redirect('book/addNewCustomerShippig');
				}

			}

		}
		}
		
	}
	function addNewCustomerShippig(){
		$data["page"] = "addNewCustomerShippig";
		$this ->form_validation->set_rules('txtfname', 'Your Name', 'trim|required');
	    $this ->form_validation->set_rules('email', 'Email', 'trim|required');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passwordConfirm]');
		$this->form_validation->set_rules('passwordConfirm', 'Password Confirmation', 'trim|required');
		
		$password = $this->input->post('password');
		$fname = $this->input->post('txtfname');
		$email = $this->input->post('email');
		if($this->form_validation->run() == FALSE){
				$this->load->view('index',$data);
		}else{
			$arr = array(
				"fullname"=>$fname,
				"email"=>$email,
				"password"=>MD5($password),
				"createdate"=>date("yyyy-mm-dd"),
				"active"=>1
			);
			$resultEmail = $this->mod_book->addNewEmailAddress($arr);
			$rowData = $this->mod_book->getUserProfile($email,$password);
				if($rowData){
					$ses_arr = array(
							"username"=>$rowData->fullname,
							"email"=>$rowData->email,
							"userId"=>$rowData->userid,
							"loggedIn"=>true
					);
				$this->session->set_userdata($ses_arr);
				redirect('book/orderCard');
			}

		}
	}


	function form_signin(){
		$data["page"] = "login";
		$this->form_validation->set_rules('txtusername', 'username', 'trim|required');		
		$this->form_validation->set_rules('txtpassword', 'password', 'trim|required');
		if($this->form_validation->run() == FALSE){
				$this->load->view('index',$data);
		}else{
			$username = $this->input->post('username');
			$password = $this->input->post('password');
			$result = $this->mod_book->form_signin($username,MD5($password));				
			if($result > 0){
				$this->session->set_userdata('loggedIn',$username);
				$this->load->view('index',$data);
			}else{

				$this->load->view('index',$data);
			}

		}
		
	}


	function addRegister_info(){
	$data["page"] = "register";
	$this->form_validation->set_rules('txtpass', 'Password', 'trim|required|matches[txtconfirmpass]');
	$this->form_validation->set_rules('txtconfirmpass', 'Password Confirmation', 'trim|required');
	$this ->form_validation->set_rules('txtfname', 'First Name', 'trim|required');
    $this ->form_validation->set_rules('txtlname', 'Last Name', 'trim|required');
	$password = $this->input->post('txtpass');
	$fname = $this->input->post('txtfname');
	$lname = $this->input->post('txtlname');
	$fullname = $fname.' '.$lname;
	$userid = $this->session->userdata('userId');
	$username = $this->session->userdata("usermail");
    if($this->form_validation->run() == FALSE){
				$this->load->view('index',$data);
	}else{
			$data = $arrayName = array('firstname' => $fname , 'lastname' => $lname , 'password' => md5($password) , 'fullname' => $fullname , 'username' => $username );

			$this->mod_book->addRegister_info($data,$userid);

			$this->session->set_userdata('register_process','done');
			
			 redirect('book/register');
			//$this->home();
		}
		
	}


	function logout(){
		$this->session->sess_destroy();
		redirect('book/home');
	}

	function validateEmail($userid){
		$this->session->set_userdata('userId',$userid);
		$this->session->set_userdata('register_process','profile');
		$this->mod_book->addActiveEmail($userid);
		redirect("book/register");

	}



}

/* controller book*/
/* directory application/controller/book.php*/
